/*************************************************
 * Imagery.java                                  *
 * Reads an image and converts each pixel into a *
 * node according to its color.                  *
 *************************************************/
package graphics;

//Imports
import arena.Arena;
import arena.Node;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

/**
 * Allows an image to be loaded and individual pixels are examined and converted
 * into nodes.
 *
 * @author      Jimmy Weston
 */
public class Imagery {

    //Variable which holds the image
    BufferedImage bimg = null;
    //New arena which is created from the image analysis
    public Arena perceivedArena;

    /**
     * Default Constructor
     */
    public Imagery() {
    }

    /**
     * Returns the dimensions of an image
     *
     * @param file  The filename of the image
     */
    public Dimension getDimension(String file) {
        try {
            BufferedImage img = ImageIO.read(new File(file));
            int width = img.getWidth();
            int height = img.getHeight();
            return new Dimension(width, height);
        } catch (Exception ex) {}
        return null;
    }

    /**
     * Generates an Arena from the image file
     *
     * @param file  The filename of the image
     */
    public Arena populateArena(String file) {
        try {
            bimg = ImageIO.read(new File(file));
            int width = bimg.getWidth();
            int height = bimg.getHeight();
            perceivedArena = new Arena(width, height);
            Color color;
            int red, blue, green;
            for (int i = width - 1; i > -1; i--) {
                for (int j = 0; j < height ; j++) {
                    color = new Color(bimg.getRGB(i, j));
                    red = color.getRed();
                    blue = color.getBlue();
                    green = color.getGreen();
                    if (red > 200 && blue > 200 && green > 200) {
                        perceivedArena.nodeMap.get(i + "," + j).setColor(Node.UNKNOWN);
                    }
                    else {
                        perceivedArena.nodeMap.get(i + "," + j).setColor(Node.DELETED);
                    }
                }
            }

            return perceivedArena;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
